<?php

namespace App\Http\Controllers;

use App\Util\Tool;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadFileController extends BaseController
{
    /**
     * base64 图片上传处理
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function doUploadFile(Request $request)
    {
        $image = $request->post('images');
        if (empty($image)) {
            return $this->ResultJson(0, '提交的数据不能为空', []);
        }
        if (!Tool::issetBase64($image)) {
            return $this->ResultJson(0, '请传入正确格式数据', []);
        }
        // 判断是否能正常解码
        if (!base64_decode($image, true)) {
            return $this->ResultJson(0, '请传入数据类型错误', []);
        }
        $image = str_replace(' ', '+', $image);
        $imagePath = 'image/' . date("Y-m-d") . DIRECTORY_SEPARATOR . strtotime("now") . rand() . '.png';
        Storage::disk('public')->put($imagePath, base64_decode($image));
        $data = ['imagePath' => $imagePath];
        return $this->ResultJson(1, '上传成功', $data);
    }
}
